package com.codingman.jpademo1;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;

public class EmployeeDao {
	public void insert(Employee employee) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("employee_unit");
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();

			em.persist(employee);

			em.getTransaction().commit();
		} finally {
			em.close();
			emf.close();
		}
	}

	public Employee findById(Integer id) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("employee_unit");
		EntityManager em = emf.createEntityManager();
		try {
			Employee employee = em.find(Employee.class, id);
			return employee;
		} finally {
			em.close();
			emf.close();
		}
	}
	
	public List<Employee> findAll() {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("employee_unit");
		EntityManager em = emf.createEntityManager();
		try {
			TypedQuery<Employee> results = em.createQuery("select e from Employee e", Employee.class);
			return results.getResultList();
		} finally {
			em.close();
			emf.close();
		}
	}
	
	public void update(Employee employee) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("employee_unit");
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();

			Employee e = em.find(Employee.class, employee.getId());
			e.setId(employee.getId());
			e.setName(employee.getName());
			e.setSalary(employee.getSalary());

			em.getTransaction().commit();
		} finally {
			em.close();
			emf.close();
		}
	}

	public void delete(Integer id) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("employee_unit");
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();

			Employee employee = em.find(Employee.class, id);
			em.remove(employee);

			em.getTransaction().commit();
		} finally {
			em.close();
			emf.close();
		}
	}
}
